//
//  DKTabBar.m
//  BTApp
//
//  Created by 丁侃 on 16/4/17.
//  Copyright © 2016年 丁侃. All rights reserved.
//

#import "DKTabBar.h"
#import "DKTabBarBtn.h"

@interface DKTabBar()

@property (nonatomic, weak) UIButton *selBtn;

@end

@implementation DKTabBar


-(void)setItems:(NSArray *)items
{
    _items = items;
    
    //添加按钮
    for (NSInteger i = 0; i < items.count; i ++) {
        
        UITabBarItem *item = items[i];
        
        DKTabBarBtn *btn = [[DKTabBarBtn alloc]init];
        
        [btn setImage:item.image forState:UIControlStateNormal];
        [btn setImage:item.selectedImage forState:UIControlStateSelected];
        [btn sizeToFit];
        
        [btn addTarget:self action:@selector(click:) forControlEvents:UIControlEventTouchUpInside];
        
        if (i == 0) {
            [self click:btn];
        }
        
        btn.tag = i;
        
        [self addSubview:btn];
    }
}

-(void)click:(DKTabBarBtn *) btn
{
    self.selBtn.selected = NO;
    
    btn.selected = YES;
    
    self.selBtn = btn;
    
    if ([self.delegate respondsToSelector:@selector(tabBar:btnDidClick:)]) {
        [self.delegate tabBar:self btnDidClick:btn];
    }
}


-(void)layoutSubviews
{
    [super layoutSubviews];
    
    CGFloat btnY = 0;
    CGFloat btnW = self.width / self.items.count;
    CGFloat btnH = self.height;
    
    //重新布局
    for ( NSInteger i = 0; i < self.items.count; i ++) {
        
        DKTabBarBtn *btn = self.subviews[i];
        
        btn.frame = CGRectMake(btnW * i, btnY, btnW, btnH);
    }
    
    
}

@end
